package pl.edu.agh.admin.core;

import it.sauronsoftware.cron4j.CronParser;
import it.sauronsoftware.cron4j.SchedulingPattern;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Calendar;
import java.util.LinkedList;
import java.util.List;

public class CRONParser {
	
	public static String getCommand(String cronLine){
		String [] tab = cronLine.split(" ");
		if(tab.length < 6){
			return null;
		}
		StringBuilder sb = new StringBuilder();
		for(int i = 5;i<tab.length;i++){
			sb.append(tab[i]);
			sb.append(" ");
		}
		String ret = sb.toString();
		return ret.substring(0, ret.length()-1);
	}
	
	public static String getPlainCron(String cronLine){
		String [] tab = cronLine.split(" ");
		if(tab.length < 5){
			return null;
		}
		StringBuilder sb = new StringBuilder();
		for(int i = 0;i<5;i++){
			sb.append(tab[i]);
			sb.append(" ");
		}
		
		return sb.toString();
	}
	
	public static List<Calendar> getAllMomentsOfExecution(String cron, Calendar until) {
		List<Calendar> retList = new LinkedList<Calendar>();
		
		try{
			long ul = until.getTimeInMillis();
			long now = Calendar.getInstance().getTimeInMillis();
			
			SchedulingPattern pattern = CronParser.parse(new ByteArrayInputStream(cron.getBytes("UTF-8"))).getSchedulingPattern(0);
			while(now < ul){
				if(pattern.match(now)){
					Calendar c = Calendar.getInstance();
					c.setTimeInMillis(now);
					retList.add(c);
				}
				now += 1000*60;
			}
		}catch (Exception e) {
			e.printStackTrace();
		}
		
		return retList;
	}
	
	public static int getNumberOfExecutions(String cron, Calendar until) {
		return getAllMomentsOfExecution(cron, until).size();
	}

	
	public static Calendar getNextTimeOfExecution(String cron) {
		Calendar cal = null;
		long i = 0;
		try{
			long now = Calendar.getInstance().getTimeInMillis();			
			SchedulingPattern pattern = CronParser.parse(new ByteArrayInputStream(cron.getBytes("UTF-8"))).getSchedulingPattern(0);
			while(cal == null && i<550000){ // more then a year
				if(pattern.match(now)){
					cal = Calendar.getInstance();
					cal.setTimeInMillis(now);
				}
				i++;
				now += 1000*60;
			}
		}catch (Exception e) {
			e.printStackTrace();
		}
		return cal;
	}
}
